package com.example.aliyunsms.controller;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.example.aliyunsms.constant.SmsContant;
import com.google.gson.Gson;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA2022.3.2
 * @Author: Tenghw
 * @Date: 2023/04/04  21:55
 * @Description: 测试阿里云给手机发短信
 */
@Slf4j
@Api(tags = "测试阿里云给手机发短信接口")
@RestController
public class SmsDemoController {

    @ApiOperation(value = "给手机发送短信")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone",value = "手机号",paramType = "query",required = true,dataType = "string",dataTypeClass = String.class)
    })
    @ApiResponse(code = 400, message = "Invalid user supplied")
    @PostMapping(path = "/send")
    public String send(@ApiParam(value = "给手机发短信", required = true)@RequestParam String phone) throws ClientException {
        // 手机号正则
        String PHONE_REGEX = "^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\\d{8}$";
        Pattern r = Pattern.compile(PHONE_REGEX);
        Matcher m = r.matcher(phone);
        System.out.println(m.matches());
        //Assert.isTrue(m.matches(),"手机号码匹配正则成功");
        if(StringUtils.isBlank(phone) || !m.matches()){
            return "手机号为空或不是1开头";
        }
        // 设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        /**
         * regionId 区域
         * accessKeyId 阿里云的秘钥id
         * accesskeySecret 阿里云的秘钥
         * template-code 模板编码
         * sign-name 签名名称
         * product 短信API产品名称
         * domain 短信API产品域名
        */
            DefaultProfile profile = DefaultProfile.getProfile(SmsContant.REGION_Id, SmsContant.KEY_ID, SmsContant.KEY_SECRET);
            try {
                /**
                 * param endpointName
                 * param regionId
                 * param product
                 * param domain
                 */
                DefaultProfile.addEndpoint(SmsContant.REGION_Id,SmsContant.REGION_Id,
                        SmsContant.PRODUCT,SmsContant.DOMAIN);
            }catch (ClientException e){
                System.out.println("RequestId: "+e.getRequestId());
                System.out.println("ErrCode: "+e.getErrCode());
                System.out.println("ErrMsg: "+e.getErrMsg());
                System.out.println("ErrorDescription: "+e.getErrorDescription());
            }
            IAcsClient client = new DefaultAcsClient(profile);
            // 组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            // 使用post请求
            request.setMethod(MethodType.POST);
            request.setSignName(SmsContant.SIGN_NAME);
            request.setTemplateCode(SmsContant.TEMPLATE_CODE);
            // 待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
            request.setPhoneNumbers(phone);
            // code 4~6位数字
            request.setTemplateParam("{\"code\":\"666888\"}");
            // 可选-上行短信扩展码(若无特殊需求，请忽略此字段)
            // request.setSmsUpExtendCode("90997");
            // 可选-outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            //request.setOutId("tenghuawei666");

            SendSmsResponse response=null;
            try {
                response = client.getAcsResponse(request);
                //if(StringUtils.equalsIgnoreCase("OK",response.getCode())){
                //    System.out.println("给手机发送验证码成功！");
                //}else {
                //    System.out.println("给手机发送验证码失败！");
                //}
                Optional<String> os1 = Optional.ofNullable(response.getCode());
                os1.filter(tipCode -> "OK".equals(tipCode)).ifPresent(x -> System.out.println("给手机发送验证码成功！"));
            }catch (ServerException e){
                e.printStackTrace();
                log.info("由于系统维护，暂时无法注册！！！");
            }
            return new Gson().toJson(response);
    }
}
